//
//  SellerCooperateTableViewController.m
//  EasyToTesco2.0
//
//  Created by 袖手旁觀 on 16/6/21.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "SellerCooperateTableViewController.h"
#import "FirstCellTableViewCell.h"
#import "SecondTableViewCell.h"
#import "SecondCellButton.h"
#import "LastTableViewCell.h"
#import "CaptchaView.h"
#import "RKAlertView.h"
#import "UserNameTableViewCell.h"
#import "LoadUserName.h"
#import "ChooseType.h"


@interface SellerCooperateTableViewController ()<SecondTableViewCellDelegate,didSubmitButtonClickDelegate,UITextFieldDelegate,SelectChooseTypeViewDelegate>

{
    // 支付方式
    NSString *fkfsStr;
    NSString *pwdStr;
    UITextField *_userNameTextField;
    
    NSString *_scale;
}

@property (nonatomic,strong)NSArray *fitstCellArray;

@property (nonatomic,strong)NSArray *thiredCellArray;

@property (nonatomic,strong)NSMutableArray *textFieldMutableArray;

@property (nonatomic,strong)UILabel *popularizeMoney;

@property (nonatomic,strong)UITextField *verificationTextField;

@property (nonatomic,strong)CaptchaView *captcha;

@property(nonatomic,strong)UILabel *balanceLabel;

@property (nonatomic,strong)ChooseType *chooseType;

@end

static NSString *const FirstReuseIdentifier = @"First";

static NSString *const SecondReuseIdentifier = @"Second";

static NSString *const ThiredReuseIdentifier = @"Thired";

static NSString *const LastFirstReuseIdentifier = @"LastFirst";

static NSString *const LastSecondReuseIdentifier = @"LastSecond";

@implementation SellerCooperateTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"商家合作专区";
    
    self.tableView.bounces = NO;
    
    self.tableView.backgroundColor = BACKGROUND_COLOR;
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    
//    self.tableView.scrollEnabled = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    fkfsStr = @"2";

    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{@"username":USERNAME} AndMenthodName:@"api/User/info" completeBlock:^(id object) {
        NSString *string = [object[@"data"] objectForKey:@"order_scale"];
        _scale = [NSString stringWithFormat:@"%.2f",string.floatValue];
    }];
    
    NSLog(@"%@----",self.cashStr);
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1){
        return 1;
    } else if (section == 2) {
        return 2;
    } else {
        return 3;
    }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        
        FirstCellTableViewCell *first = [tableView dequeueReusableCellWithIdentifier:FirstReuseIdentifier];
        
        if (!first) {
            first = [[FirstCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:FirstReuseIdentifier];
            first.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        first.firstLabel.text = [self.fitstCellArray[indexPath.row] objectForKey:@"label"];
        first.firstLabel.numberOfLines = 0;
        
        first.inPutTextField.placeholder = [self.fitstCellArray[indexPath.row] objectForKey:@"placeholder"];
        
        first.inPutTextField.tag = indexPath.row;
        
        first.inPutTextField.userInteractionEnabled = NO;
        
        [self.textFieldMutableArray addObject:first.inPutTextField];
        
        if (indexPath.row == 0) {
            first.inPutTextField.delegate = self;
        } else {
            first.inPutTextField.keyboardType = UIKeyboardTypeNumberPad;
        }
        
        
        
        return first;
    } else if (indexPath.section == 1) {
        SecondTableViewCell *second = [tableView dequeueReusableCellWithIdentifier:SecondReuseIdentifier];
        
        if (!second) {
            second = [[SecondTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SecondReuseIdentifier];
            second.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        second.delegate = self;
        
        return second;
    } else if (indexPath.section == 2) {
        
        FirstCellTableViewCell *thired = [tableView dequeueReusableCellWithIdentifier:ThiredReuseIdentifier];
        
        if (!thired) {
            thired = [[FirstCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ThiredReuseIdentifier];
            
            thired.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        thired.firstLabel.text = [self.thiredCellArray[indexPath.row]objectForKey:@"label"];
        thired.inPutTextField.placeholder = [self.thiredCellArray[indexPath.row] objectForKey:@"placeholder"];
        thired.inPutTextField.keyboardType = UIKeyboardTypeNumberPad;
        
        if (indexPath.row == 0) {
            thired.inPutTextField.tag = 1;
            thired.inPutTextField.delegate = self;
            thired.inPutTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
            [self.textFieldMutableArray addObject:thired.inPutTextField];
            [thired.inPutTextField addTarget:self action:@selector(didPopularizeTextFieldChangeMoney:) forControlEvents:UIControlEventEditingChanged];
        } else {
            thired.balanceLabel.hidden = false;
            thired.rightLabel.hidden = NO;
            thired.inPutTextField.hidden = YES;
            thired.inPutTextField.keyboardType = UIKeyboardTypeNumberPad;
 
            self.balanceLabel = thired.balanceLabel;
            self.popularizeMoney = thired.rightLabel;
        }
        return thired;
    } else {
        
        if (indexPath.row == 0) {
            FirstCellTableViewCell *lastFirst = [tableView dequeueReusableCellWithIdentifier:LastFirstReuseIdentifier];
            
            if (!lastFirst) {
                lastFirst = [[FirstCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:LastFirstReuseIdentifier];
                lastFirst.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            lastFirst.firstLabel.text = @"用户名";
            
            lastFirst.inPutTextField.placeholder = @"请输入用户名";
            lastFirst.inPutTextField.keyboardType = UIKeyboardTypeNumberPad;
            lastFirst.inPutTextField.clearButtonMode = UITextFieldViewModeAlways;
            [lastFirst.inPutTextField addTarget:self action:@selector(didClickUserNumberChangeName:)forControlEvents:UIControlEventEditingChanged];
            lastFirst.tag = 2;
            [self.textFieldMutableArray addObject:lastFirst.inPutTextField];
            
            return lastFirst;
        } else if (indexPath.row == 1) {
        
            UserNameTableViewCell *fourSecond = [tableView dequeueReusableCellWithIdentifier:@"four"];
            if (fourSecond == nil) {
                fourSecond = [[UserNameTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"four"];
                
                fourSecond.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            fourSecond.firstLabel.text = @"真实姓名";
            
            fourSecond.firstLabel.numberOfLines = 0;
            
            fourSecond.inPutTextField.userInteractionEnabled = NO;
            
            fourSecond.inPutTextField.placeholder = @"请核实姓名";
            
            _userNameTextField = fourSecond.inPutTextField;
            
            fourSecond.inPutTextField.tag = 3;
            [self.textFieldMutableArray addObject:fourSecond.inPutTextField];
                        
            return fourSecond;
            
        } else {
            LastTableViewCell *lastCell = [tableView dequeueReusableCellWithIdentifier:LastSecondReuseIdentifier];
            
            if (!lastCell) {
                lastCell = [[LastTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:LastSecondReuseIdentifier];
                
                lastCell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            lastCell.delegate = self;
            lastCell.verificationTextField.tag = 4;
            lastCell.verificationTextField.delegate = self;
            self.verificationTextField = lastCell.verificationTextField;
            self.captcha = lastCell.Captcha;
            [self.textFieldMutableArray addObject:lastCell.verificationTextField];
            
            return lastCell;
        }
        
    }
}

- (void)didClickUserNumberChangeName :(UITextField *)textField {
    
    UITextField *sellerNumber = self.textFieldMutableArray[2];
    
    if (textField == sellerNumber) {
        if (textField.text.length >=11) {
            textField.text = [textField.text substringToIndex:11];
        }
        if (textField.text.length >10) {
            [LoadUserName loadUserNameWithPhoneNumber:sellerNumber.text andCompleteUserName:^(NSString *userName) {
                if (userName.length) {
                    _userNameTextField.text = userName;
                } else {
                    _userNameTextField.text = @"未绑定";
                }
            } and:self.view];
        } else {
            _userNameTextField.text = @"";
        }
    }
    
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        return 88;
    } else if  (indexPath.section == 3 && indexPath.row == 2) {
        return HEIGHT - 338-64+34 - 44;
    } else if(indexPath.section == 0) {
        return 70;
    }else{
        return 44;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return 0.001;
    }
    
    return 5;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self clearAllTextFieldResignFirstResponder];
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{} AndMenthodName:@"api/Hz/types" completeBlock:^(id object) {
            NSArray *array = [object[@"data"] objectForKey:@"types"];
            self.chooseType = [[ChooseType alloc] initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT)WithDataArray:array];
            self.chooseType.delegate = self;
            [self.view addSubview:self.chooseType];
            [self.chooseType showPickerView];
            
        }];
    }
}

- (void)SelectChooseTypeViewCityStr:(NSString *)typeName {
    UITextField *textField = self.textFieldMutableArray[0];
    textField.text = typeName;
}

- (void)SelectChooseTypeViewCancle {
    [self.chooseType dismissPickerView];
}

- (void)SecondTableViewCellButtonDelegate:(SecondCellButton *)SecondButton {
    NSLog(@"%ld",SecondButton.tag);

    
    if (SecondButton.tag == 1) {
//        现金
        self.balanceLabel.text = [NSString stringWithFormat:@"充值账户:%@",self.cashStr];
        fkfsStr = @"1";
    } else {
//        积分
        fkfsStr = @"2";
        self.balanceLabel.text = @"";

    }
}

- (void)didSubmitButtonClick:(UIButton *)submitButton {
    
    NSLog(@"%s",__func__);
    
    UITextField *productName = self.textFieldMutableArray[0];
    
//    UITextField *productNumber = self.textFieldMutableArray[1];
    
    UITextField *productMoney = self.textFieldMutableArray[1];
    
    UITextField *phoneNumber = self.textFieldMutableArray[2];
    
    if ((productName.text.length == 0)||(productMoney.text.length == 0)||(phoneNumber.text.length == 0)||(self.verificationTextField.text.length == 0)) {
        
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"请确认信息输入无误" toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [self.view addSubview:hud];
    } else {
        if (([productMoney.text floatValue] <=0)) {
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"金额必须大于0" toView:self.view dimBackground:NO AndCompleteBlock:nil];
            [self.view addSubview:hud];
        } else if (![self.verificationTextField.text isEqualToString:self.captcha.changeString]) {
            
            [self textFieldAnimation:self.verificationTextField andSecondTextField:self.captcha.layer];
        } else {
//            弹出密码输入框
            if ([fkfsStr isEqualToString:@"2"]) {
                [RKAlertView showAlertPlainTextWithTitle:@"请输入二级密码" message:nil cancelTitle:@"取消" confirmTitle:@"确认" alertViewStyle:UIAlertViewStylePlainTextInput confrimBlock:^(UIAlertView *alertView) {
                    NSLog(@"确认了输入：%@",[alertView textFieldAtIndex:0].text);
                    pwdStr = [alertView textFieldAtIndex:0].text;
                    NSLog(@"%@",pwdStr);
                    
                    [self shopuserUNdatasources];
                    
                } cancelBlock:^{
                    //       NSLog(@"取消了");
                }];
            } else {
                
                [self shopuserUNdatasources];
            }
            
        }
    }
}

- (void)didPopularizeTextFieldChangeMoney:(UITextField *)textField {
    
    UITextField *popularizeTextField = self.textFieldMutableArray[1];
    
    if (textField == popularizeTextField) {
        NSLog(@"%@",textField.text);
        self.popularizeMoney.text = [NSString stringWithFormat:@"%.2f",textField.text.floatValue * _scale.floatValue];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    UITextField *popularizeTextField = self.textFieldMutableArray[1];
    
    if (textField == popularizeTextField) {
        BOOL isHaveDian = YES;
        if ([textField.text rangeOfString:@"."].location==NSNotFound) {
            isHaveDian=NO;
        }
        if (string.length) {
            unichar single=[string characterAtIndex:0];//当前输入的字符
            
            if ((single >='0' && single<='9') || single=='.')//数据格式正确
            {
                //首字母不能为小数点
                if([textField.text length]==0){
                    if(single == '.'){
                        [textField.text stringByReplacingCharactersInRange:range withString:@""];
                        return NO;
                        
                    }
                }
            } else {
                return NO;
            }
            
            if (single=='.') {
                if(!isHaveDian){
                    //text中还没有小数点
                    
                    isHaveDian=YES;
                    return YES;
                } else {
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            } else {
                if (isHaveDian) {
                    //存在小数点
                    //判断小数点的位数
                    NSRange ran=[textField.text rangeOfString:@"."];
                    NSInteger tt=range.location-ran.location;
                    if (tt <= 1){
                        return YES;
                    }else{
                        return NO;
                    }
                } else {
                    return YES;
                }
            }
        }
    }
    
    return YES;
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField {
 
    UITextField *oneCellFirstTextField = self.textFieldMutableArray[0];
    
    UITextField *oneCellSecondTextField = self.textFieldMutableArray[1];
    
    if (textField == oneCellFirstTextField) {
     
        [oneCellSecondTextField becomeFirstResponder];
    }
    
    return YES;
    
}

- (void)textFieldAnimation:(UITextField *)inPutTextField andSecondTextField:(CALayer *)SecondTextField {
    if (![inPutTextField.text isEqualToString:self.captcha.changeString]) {
        NSLog(@"%@",self.captcha.changeString);
        //验证不匹配，验证码和输入框晃动
        CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
        anim.repeatCount = 1;
        anim.values = @[@-10, @10, @-10];
        [SecondTextField addAnimation:anim forKey:nil];
        [inPutTextField.layer addAnimation:anim forKey:nil];
    }

}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    UITextField *lasTextField = self.textFieldMutableArray.lastObject;
    
    if (textField == self.verificationTextField) {
        if (![textField.text isEqualToString:self.captcha.changeString]) {
            [self textFieldAnimation:textField andSecondTextField:lasTextField.layer];
        }
    }
    
}

- (void)clearAllTextFieldResignFirstResponder {
 
    for (UITextField *textField in self.textFieldMutableArray) {
        
        [textField resignFirstResponder];
        
        if (textField == self.textFieldMutableArray[1]) {
            self.popularizeMoney.text = [NSString stringWithFormat:@"%.2f",textField.text.floatValue * _scale.floatValue];
        }
    }
}

- (void)shopuserUNdatasources {
    UITextField *productName = self.textFieldMutableArray[0];
    
//    UITextField *productNumber = self.textFieldMutableArray[1];
    
    UITextField *productMoney = self.textFieldMutableArray[1];
    
    UITextField *phoneNumber = self.textFieldMutableArray[2];
    
    NSString *title = [NSString stringWithFormat:@"%@", productName.text];
    
    NSDictionary *params = @{
                             @"title":title,
                             @"jine":productMoney.text,
                             @"pay_type":[NSString stringWithFormat:@"%@", fkfsStr],
                             @"username":phoneNumber.text,
                             @"uname":USERNAME,
                             @"pwdtwo":[NSString stringWithFormat:@"%@", pwdStr]
                             };
    
    
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Cooperation/newAdd" completeBlock:^(id object) {
        NSLog(@"%@",object);
        [JudgeBackDataCodeMessage JudgeBackDataCodeMessage:@"操作成功" andObjece:object andAddHUDView:self.view andPopViewController:^(id object) {
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                for (UITextField *textField in self.textFieldMutableArray) {
                    textField.text = nil;
                }
                self.popularizeMoney.text = @"0.00";
            });

        }];
    }];
}


- (NSArray *)fitstCellArray {
    if (!_fitstCellArray) {
        _fitstCellArray = @[
                            @{
                                @"label":@"购买产品及其数量",
                                @"placeholder":@"请输入购买产品的名称及数量"
                                }
                            ];
    }
    return _fitstCellArray;
}

- (NSArray *)thiredCellArray {
    if (!_thiredCellArray) {
        _thiredCellArray = @[
                             @{
                                 @"label":@"产品金额",
                                 @"placeholder":@"请输入产品金额"
                                 },
                             
                             @{
                                 @"label":@"产品推广费",
                                 @"placeholder":@""
                                 }
                             ];
    }
    return _thiredCellArray;
}

- (NSMutableArray *)textFieldMutableArray {
    if (!_textFieldMutableArray) {
        _textFieldMutableArray = [NSMutableArray array];
    }
    return _textFieldMutableArray;
}



@end
